
from tornado import web, websocket, escape
from datetime import datetime

clients = set()


class UserMixin:

    @property
    def current_user(self):
        user = self.get_secure_cookie("username")
        if user:
            return user.decode("utf-8")
        else:
            return ""


class IndexHandler(UserMixin, web.RequestHandler):

    def get(self, *args, **kwargs):

        if not self.current_user:
            self.render("login.html")
        else:
            self.render("index.html", username=self.current_user)

    def post(self, *args, **kwargs):

        username = self.get_body_argument("username")
        self.set_secure_cookie("username", username)

        self.render("index.html", username=self.current_user)


class WSHandler(UserMixin, websocket.WebSocketHandler):

    def open(self, *args, **kwargs):
        clients.add(self)

    def on_message(self, message):

        _message = escape.json_decode(message)
        message = {
            "username": self.current_user,
            "body": _message['content'],
            "datetime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }

        message['html'] = escape.to_basestring(
            self.render_string("msg.html", **message)
        )
        _todo_delete = []
        for client in clients:
            try:
                client.write_message(message)
            except websocket.WebSocketClosedError:
                _todo_delete.append(client)

        for client in _todo_delete:
            clients.remove(client)

    def on_close(self):
        pass
